package com.shiku.mianshi.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.mongodb.morphia.Datastore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

import cn.xyz.commons.support.jedis.JedisTemplate;
import cn.xyz.commons.utils.ReqUtil;
import cn.xyz.commons.vo.JSONMessage;
import cn.xyz.mianshi.service.FriendsManager;
import cn.xyz.mianshi.service.impl.UserManagerImpl;
import cn.xyz.mianshi.utils.ConstantUtil;
import cn.xyz.mianshi.vo.Fans;
import cn.xyz.service.BaiduPushService;
import cn.xyz.service.KXMPPServiceImpl;
import cn.xyz.service.KXMPPServiceImpl.MessageBean;

/**
 * Tigase支持接口
 * 
 * @author Administrator
 *
 */
@RestController
@RequestMapping("/tigase")
public class TigaseController extends AbstractController {

	@Resource(name = "dsForTigase")
	private Datastore dsForTigase;
	@Resource(name = "jedisTemplate")
	protected JedisTemplate jedisTemplate;
	@Autowired
	private FriendsManager friendsManager;
	@Autowired
	private UserManagerImpl userManager;

	
	
	@RequestMapping("/shiku_msgs")
	public JSONMessage getMsgs(@RequestParam int receiver, @RequestParam(defaultValue = "0") long startTime,
			@RequestParam(defaultValue = "0") long endTime, @RequestParam(defaultValue = "0") int pageIndex,
			@RequestParam(defaultValue = "10") int pageSize) {
		int sender = ReqUtil.getUserId();
		DBCollection dbCollection = dsForTigase.getDB().getCollection("shiku_msgs");
		BasicDBObject q = new BasicDBObject();
		q.put("sender", sender);
		q.put("receiver", receiver);
		if (0 != startTime)
			q.put("ts", new BasicDBObject("$gte", startTime));
		if (0 != endTime)
			q.put("ts", new BasicDBObject("$lte", endTime));

		java.util.List<DBObject> list = Lists.newArrayList();

		DBCursor cursor = dbCollection.find(q).sort(new BasicDBObject("_id", -1)).skip(pageIndex * pageSize)
				.limit(pageSize);
		while (cursor.hasNext()) {
			list.add(cursor.next());
		}

		return JSONMessage.success("", list);
	}

	@RequestMapping("/shiku_muc_msgs")
	public JSONMessage getMucMsgs(@RequestParam String roomId, @RequestParam(defaultValue = "0") long startTime,
			@RequestParam(defaultValue = "0") long endTime, @RequestParam(defaultValue = "0") int pageIndex,
			@RequestParam(defaultValue = "10") int pageSize) {

		DBCollection dbCollection = dsForTigase.getDB().getCollection("shiku_muc_msgs");
		BasicDBObject q = new BasicDBObject();
		q.put("room_jid_id", roomId);
		if (0 != startTime)
			q.put("ts", new BasicDBObject("$gte", startTime));
		if (0 != endTime)
			q.put("ts", new BasicDBObject("$lte", endTime));

		java.util.List<DBObject> list = Lists.newArrayList();

		DBCursor cursor = dbCollection.find(q).sort(new BasicDBObject("_id", -1)).skip(pageIndex * pageSize)
				.limit(pageSize);
		while (cursor.hasNext()) {
			list.add(cursor.next());
		}

		return JSONMessage.success("", list);
	}

	@RequestMapping(value = "/notify")
	public JSONMessage notify(@RequestParam Long from, @RequestParam Long to, @RequestParam String body,
			@RequestParam long ts) {
		try {
			//String c = new String(body.getBytes("iso8859-1"),"utf-8");
			//System.out.println(c);
			String key1 = String.format("user:%s:channelId", to);
			String key2 = String.format("user:%s:deviceId", to);
			String channelId = jedisTemplate.get(key1);
			String deviceId = jedisTemplate.get(key2);
			if (null != deviceId && null != channelId) {
				String key3 = String.format("channelId:%s", channelId);
				String toUserId = jedisTemplate.get(key3);
				// channeId没有设置对应的userId或者对应的userId等于消息接收方
				if (!StringUtils.hasText(toUserId) || Integer.parseInt(toUserId) == to) {
					int messageType = 0;
					String text = "";
					String fromUserName = "";
					try {
						JSONObject jsonObj = JSON
								.parseObject(body);
						messageType = jsonObj.getInteger("type");
						fromUserName = jsonObj.getString("fromUserName");
						
						if (1 == messageType) {
							text = jsonObj.getString("content");
							if (StringUtils.hasText(text)) {
								if (text.length() > 20)
									text = text.substring(0, 20) + "...";
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					
					BaiduPushService.PushMessage msg = new BaiduPushService.PushMessage(from, fromUserName, to, text,
							messageType, ts);
					String appId=userManager.get(new Integer(from.toString())).getAppId();
					BaiduPushService.pushSingle(Integer.parseInt(deviceId), channelId, msg,appId);
					return JSONMessage.success();
				} else {
					return JSONMessage.success();
				}
			} else {
				System.out.println("离线推送：未发现匹配的与用户匹配的推送通道Id");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return JSONMessage.failure("推送失败");
	}
	@RequestMapping(value = "/push")
	public JSONMessage push(@RequestParam String text, @RequestParam String body) {
		System.out.println("push");
		List<Integer> userIdList = JSON.parseArray(text, Integer.class);
		try {
			//String c = new String(body.getBytes("iso8859-1"),"utf-8");
			KXMPPServiceImpl.getInstance().send(userIdList, body);
			return JSONMessage.success();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return JSONMessage.failure("推送失败");
		// {userId:%1$s,toUserIdList:%2$s,body:'%3$s'}
	}
	
	@RequestMapping(value = "/OnlineState")
	public JSONMessage OnlineState(@RequestParam long userId, @RequestParam int OnlineState) {		
		List<Fans> data = friendsManager.getFansList((int)userId);
		List<Integer>userlist=new ArrayList<>();
		MessageBean messageBean = new MessageBean();
		messageBean.setFromUserId(Long.toString(userId));
		for (Fans fans : data) {
			userlist.add(fans.getToUserId());
		}
		if (OnlineState==0) {
			messageBean.setType(KXMPPServiceImpl.OFFLINE);
		}else{
			messageBean.setType(KXMPPServiceImpl.ONLINE);
		}
		try {
			KXMPPServiceImpl.getInstance().send(userlist, messageBean.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return JSONMessage.failure("推送失败");
	}

	
	
//	删除消息接口(阅后即焚)
	@RequestMapping("/deleteMsg")
	public JSONMessage deleteMsg(@RequestParam String messageId) throws Exception{
		
		DBCursor cursor = null;
		try{
			DBCollection dbCollection = dsForTigase.getDB().getCollection("shiku_msgs");
		
			BasicDBObject query = new BasicDBObject();
			
			
			query.put("body",new BasicDBObject("$regex", messageId)); //模糊查询
			cursor = dbCollection.find(query);
			if(cursor.size()>0){
				
				BasicDBObject dbObj = (BasicDBObject) cursor.next();
				//解析消息体
				
				Map<String,Object> body = JSON.parseObject(dbObj.getString("body").replace("&quot;", "\""), Map.class);
				int type = (int) body.get("type"); 
				
				
				dbCollection.remove(query); //将消息记录中的数据删除	
				
				/**
				Type = 1,//文本
			    Type = 2,//图片
			    Type = 3,//语音
			    Type=4, //位置
			    Type=5,//动画
			    Type=6,//视频
			    Type=7,//音频
			    Type=8,//名片
			    Type=9, //文件
			    Type=10, //提醒
				 */
				if(type==2 || type==3 || type==5 || type==6 || type==7 || type==9){
					String paths = (String) body.get("content");
					//调用删除方法将文件从服务器删除
					ConstantUtil.deleteFile(paths);
				}
				
				}else{
                   return JSONMessage.error(new RuntimeException("删除失败，请重试!")); 
				}
				
			} catch (Exception e){
				e.printStackTrace();
			}finally {
				if(cursor != null) cursor.close(); 
			}
		
		return JSONMessage.success();
		
	}
	
	
}





















